package com.atguigu.crowd.mvc.controller;

import com.atguigu.crowd.service.MenuService;
import com.atguigu.crowd.util.ResultEntity;
import com.atguigu.entity.Menu;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@RestController
public class MenuController {
    @Autowired
    private MenuService menuService;


    @RequestMapping("/menu/remove")
    public ResultEntity<String> removeMenu(Integer id){
        menuService.removeMenu(id);
        return ResultEntity.successData();
    }


    @RequestMapping("/menu/save")
    public ResultEntity<String> saveMenu(Menu menu){

        menuService.saveMenu(menu);

        return ResultEntity.successData();
    }


    @RequestMapping("/menu/update")
    public ResultEntity<String> updateMenu(Menu menu){
        menuService.updateMenu(menu);
        return ResultEntity.successData();
    }


    @RequestMapping("/menu/get/whole/tree")
    public ResultEntity<Menu> getWholeTreeNew(){
        List<Menu> menuList = menuService.getAll();
        // 声明一个变量用来存储找到的根节点
        Menu root = null;

        // 创建一个map对象用来存储id和Menu对象的关系
        Map<Integer,Menu> menuMap = new HashMap<>();

        // 遍历menuList填充menuMap
        for (Menu menu:
             menuList) {
            Integer id = menu.getId();


            menuMap.put(id,menu);
        }
        // 再一次遍历menuList查找根节点、组装父子节点
        for (Menu menu:
             menuList) {
            // 获取当前menu对象的pid
            Integer pid = menu.getPid();
            if (pid == null){
                // 说明找到根节点了

                root = menu;
                // 执行下一次循环
                continue;
            }
            // 如果pid不为null，说明当前节点有父节点，menuMap找到父节点
            Menu menuFather = menuMap.get(pid);

            // 将当前节点存入父节点
            menuFather.getChildren().add(menu);

        }

        // 将根节点返回给浏览器
        return ResultEntity.successResuleData(root);
    }

}
